#!/usr/bin/env python
'''
DocIndexer Open Office odt parser.
'''
from abstract_parser import AbstractParser
from common import EDocIndexer
import zipfile
import xml.dom.minidom

# From my odf2text.py script.
def nodetext(node):
    n = node.firstChild
    result = ''
    while n:
        if n.nodeType == n.TEXT_NODE:
            result += n.data + '\n'
        elif n.nodeType == n.ELEMENT_NODE:
            result += nodetext(n)
        n = n.nextSibling
    return result

def extract_text(filename):
    z = zipfile.ZipFile(filename)
    try:
        doc = z.read('content.xml')
    finally:
        z.close()
    doc = doc[doc.index('<?xml'):]  # Strip leading MIME type.
    dom = xml.dom.minidom.parseString(doc)
    return nodetext(dom.documentElement)

class Parser(AbstractParser):

    description = 'Open Office otd document parser'
    mime_types = ['application/vnd.oasis.opendocument.text']

    def text(self,filename):
        try:
            return extract_text(filename)
        except:
            raise EDocIndexer,'unable to parse document'


if __name__ == '__main__':
    Parser.test()

# vim: ts=4 sw=4:

